<template>
    <div class="page">
        <div class="card-box">
            <div class="card">
                <el-form inline :model="searchInfo">
                  <el-form-item label="parrent-ID:">
                    <el-input v-model.number="searchInfo.parent_id" placeholder="请输入parent id" type="number"></el-input>
                  </el-form-item>
                  <el-form-item label="ID:">
                    <el-input v-model.number="searchInfo.id" placeholder="请输入id" type="number"></el-input>
                  </el-form-item>
                  <el-form-item label="条件名称:">
                    <el-input v-model="searchInfo.name" placeholder="请输入条件名称"></el-input>
                  </el-form-item>
                  <el-form-item label="条件级别:">
                    <el-input v-model.number="searchInfo.level" placeholder="请输入条件级别" type="number"></el-input>
                  </el-form-item>
                  <el-form-item label="状态:">
                    <el-select v-model="searchInfo.status" clearable placeholder="请选择状态" @change="statusSelectChange">
                      <el-option v-for="item in statusOptions" 
                      :key="item.value" 
                      :label="item.label"
                      :value="item.value"></el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" icon="search" @click="onSearch">查询</el-button>
                    <el-button icon="refresh" @click="onReset">重置</el-button>
                  </el-form-item>
                </el-form>
            </div>
        </div>
        <div class="card-box">
            <div class="card">
                <el-button type="primary" icon="plus" @click="onAdd">新增</el-button>
                <el-button icon="delete" @click="onDelete">删除</el-button>
                <el-table :data="tableData" style="margin-top: 10px;" @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="55"></el-table-column>
                    <el-table-column label="parent id" prop="parent_id"></el-table-column>
                    <el-table-column label="id" prop="id"></el-table-column>
                    <el-table-column label="条件名称" prop="name"></el-table-column>
                    <el-table-column label="权重" prop="sort"></el-table-column>
                    <el-table-column label="选择类型">
                        <template #default="scope">
                            {{ formatSelectType(scope.row.multi_select) }}
                        </template>
                    </el-table-column>
                    <el-table-column label="状态">
                        <template #default="scope">
                            {{ formatStatus(scope.row.status) }}
                        </template>
                    </el-table-column>
                    <el-table-column label="按钮组">
                      <template #default="scope">
                        <el-button type="primary" link icon="edit" @click="onEdit(scope.row)">修改</el-button>
                      </template>
                      
                    </el-table-column>
                </el-table>
                <div style="display: flex;justify-content: flex-end;padding: 20px;">
                    <el-pagination 
                    :total="total" 
                    :current-page="page"  
                    :page-size="pageSize" 
                    :page-sizes="[10, 30, 50, 100]"
                    @current-change="handleCurrentChange"
                    @size-change="handleSizeChange"
                    layout="total, sizes, prev, pager, next, jumper"></el-pagination>
                </div>
            </div>
        </div>

        <el-dialog v-model="editDialogVisible" :title="isAdd ? '新增' : '编辑'">
            <el-form :model="editInfo">
              <el-form-item label="父条件id">
                <el-input v-model.number="editInfo.parent_id" placeholder="请输入父条件id" clearable type="number"></el-input>
              </el-form-item>
              <el-form-item label="条件名称">
                <el-input v-model="editInfo.name" placeholder="请输入条件名称" clearable></el-input>
              </el-form-item>
              <el-form-item label="权重">
                <el-input v-model.number="editInfo.sort" placeholder="请输入权重" clearable type="number"></el-input>
              </el-form-item>
              <el-form-item label="状态:">
                <el-select v-model="editInfo.status" clearable placeholder="请选择状态" @change="editStatusSelectChange">
                  <el-option v-for="item in statusOptions" 
                  :key="item.value" 
                  :label="item.label"
                  :value="item.value"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="图片">
                <div style="display: flex;">
                  <div v-for="(item, index) in editInfoPictures" style="margin-right: 5px;">
                    <div style="width: 100px;height: 100px; border: 1px dashed #ccc;margin-bottom: 5px;">
                      <img v-if="item.picture.url" style="width: 100%; height: 100%;" :src="IMAGE_BASE_URL + item.picture.url">
                      <img v-else-if="item.picture.fileUrl" style="width: 100%; height: 100%;" :src="item.picture.fileUrl">
                      <div v-else>错误</div>
                    </div>
                    <el-select v-model="item.status" placeholder="请选择类型" style="width: 100px; display: block; margin-bottom: 5px;">
                      <el-option v-for="item in conditionPictureStatusOptions" 
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"></el-option>
                    </el-select>
                    <el-button type="primary" style="width: 100px;margin-bottom: 10px;" @click="onPictureDelete(index)">删除</el-button>
                  </div>

                  <div class="edit-picture-add">
                    <div style="width: 100px;height: 100px;border-radius: 20px;border: 1px dashed #ccc; margin-bottom: 5px;">
                      <el-upload
                        :show-file-list="false"
                        :auto-upload="false"
                        :multiple="false"
                        accept="image/*"
                        :on-change="onPictureSelect"
                        >
                        <div style="width: 100px;height: 100px;">
                          <div v-if="editDialogPictureInput.picture" style="width: 100%; height: 100%;">
                            <img v-if="editDialogPictureInput.picture.url" style="width: 100%; height: 100%;" :src="IMAGE_BASE_URL + editDialogPictureInput.picture.url">
                            <img v-else-if="editDialogPictureInput.picture.fileUrl" style="width: 100%; height: 100%;" :src="editDialogPictureInput.picture.fileUrl">
                            <div v-else>错误</div>
                          </div>
                          <div v-else style="width: 100%;height: 100%; display: flex;justify-content: center; align-items: center;">
                            <el-icon size="28px">
                              <Plus />
                            </el-icon>
                          </div>
                        </div>
                      </el-upload>
                    </div>
                    <el-select v-model="editDialogPictureInput.status" placeholder="请选择类型" style="width: 100px; display: block; margin-bottom: 5px;">
                      <el-option v-for="item in conditionPictureStatusOptions" 
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"></el-option>
                    </el-select>
                    <el-button type="primary" style="width: 100px;margin-bottom: 10px;" @click="onPictureAdd">添加</el-button>
                  </div>
                  
                </div>
              </el-form-item>
              <el-form-item label="选择类型">
                <el-select v-model="editInfo.multi_select" placeholder="请选择选择类型" style="width: 100px; display: block; margin-bottom: 5px;">
                  <el-option v-for="item in conditionSelectType" 
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"></el-option>
                </el-select>
              </el-form-item>
            </el-form>
            <template #footer>
                <div>
                    <el-button @click="editDialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="onSave">确 定</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script>
export default {
  name: 'ConditionManager',
}
</script>

<script setup>
import { watch, ref, } from 'vue';
import { 
    createCondition, 
    updateCondition,
    deleteConditionList,
    getConditionList,
} from '@/api/condition'
import {
  uploadPicture
} from '@/api/upload'
import { ElMessage } from "element-plus"
import { getFileMd5 } from "@/utils/md5"
import {IMAGE_BASE_URL, statusOptions, formatStatus, conditionPictureStatusOptions, formatSelectType, conditionSelectType} from "@/common/const";


const searchInfo = ref({})

const page = ref(1)
const pageSize = ref(10)
const total = ref(0)
const tableData = ref([])

const editDialogVisible = ref(false)
const editDialogPictureInput = ref({})
const editInfoPictures = ref([])
const isAdd = ref(false)
const editInfo = ref({})
const selectRows = ref([])

const statusSelectChange= (val) => {
    if (val) {
        searchInfo.value.status = val
    } else {
        searchInfo.value.status = null
    }
}

const editStatusSelectChange= (val) => {
    if (val) {
        editInfo.value.status = val
    } else {
        delete editInfo.value.status
    }
}


const onSearch = () => {
    page.value = 1
    pageSize.value = 10
    getTableData()
}
const onReset = () => {
    searchInfo.value = {}
}


const onAdd = () => {
  isAdd.value = true
  editInfo.value = { status: 2 }
  editDialogPictureInput.value = { }
  editInfoPictures.value = []
  editDialogVisible.value = true
}

const onEdit = (row) => {
  isAdd.value = false
  editInfo.value = { ...row }
  editDialogPictureInput.value = { }
  let items = []
  if (row.pictures) {
    let pictures = JSON.parse(row.pictures)
    for (let index = 0; index < pictures.length; index++) {
      const element = pictures[index];
      items.push({
        picture: {
          file: null,
          fileUrl: '',
          url: element.url,
          width: element.width,
          height: element.height,
        }, 
        status: element.status
      })
    }
  }
  editInfoPictures.value = items
  editDialogVisible.value = true
}

const onPictureSelect = (uploadFile, uploadFiles) => {
  editDialogPictureInput.value.picture = {
      file: uploadFile.raw,
      fileUrl: URL.createObjectURL(uploadFile.raw),
      url:'',
      width:0,
      height:0,
  }
}

const onPictureAdd = () => {
  if (editDialogPictureInput.value.picture && editDialogPictureInput.value.status){
    editInfoPictures.value.push(editDialogPictureInput.value)
    editDialogPictureInput.value = { }
  }
}

const onPictureDelete = (index) => {
  editInfoPictures.value.splice(index, 1)
}



const onDelete = async() => {
  const ids = selectRows.value.map(item => item.id)
  const res = await deleteConditionList({ ids })
  if (res.code === 0) {
    ElMessage({
      type: 'success',
      message: res.msg
    })
    if (tableData.value.length === ids.length && page.value > 1) {
      page.value--
    }
    getTableData()
  } else {
    ElMessage({
      type: 'error',
      message: `${res.msg}`,
      showClose: true
    })
  }
}

const onSave = async() => {

  var uploadReqList = []
  var uploadResultMap = new Map()
  for (let index = 0; index < editInfoPictures.value.length; index++) {
    const element = editInfoPictures.value[index];
    if(element.picture.file) {
      let md5 = await getFileMd5(element.picture.file)
      uploadResultMap.set(md5, element)
      let fd = new FormData()
      fd.append('file', element.picture.file)
      uploadReqList.push(uploadPicture(fd))
    }
  }

  if(uploadReqList.length > 0){
    let uploadResult = await Promise.all(uploadReqList)
    .catch(error => console.error(error));
    for (let index = 0; index < uploadResult.length; index++) {
      const element = uploadResult[index];
      const item = uploadResultMap.get(element.data.md5)
      item.picture.url = element.data.url
      item.picture.width = element.data.width
      item.picture.height = element.data.height
    }
  }

  var pictures = []
  for (let index = 0; index < editInfoPictures.value.length; index++) {
    const element = editInfoPictures.value[index];
    pictures.push({
      status: element.status,
      url: element.picture.url,
      width: element.picture.width,
      height: element.picture.height
    })
  }
  editInfo.value.req_images = pictures

  var res
  if(isAdd.value){
    res = await createCondition(editInfo.value)
  } else {
    res = await updateCondition(editInfo.value)
  }

  if(res.code === 0){
    editDialogVisible.value = false
    ElMessage({
      type: 'success',
      message: "操作成功",
      showClose: true
    })
    getTableData()
  } else {
    ElMessage({
      type: 'error',
      message: `${res.msg}`,
      showClose: true
    })
  }

}



// 批量操作
const handleSelectionChange = (val) => {
  selectRows.value = val
}
// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  getTableData()
}
const handleCurrentChange = (val) => {
  page.value = val
  getTableData()
}

const getTableData = async() => {
    try {
        if (!searchInfo.value.parent_id && (searchInfo.value.parent_id !== 0)){
          delete searchInfo.value.parent_id
        }
        if (!searchInfo.value.id && (searchInfo.value.id !== 0)){
          delete searchInfo.value.id
        }
        if (!searchInfo.value.level && (searchInfo.value.level !== 0)){
          delete searchInfo.value.level
        }
        if (!searchInfo.value.name){
          delete searchInfo.value.name
        }
        const res = await getConditionList({page: page.value, page_size: pageSize.value, ...searchInfo.value})
        if(res.code === 0){
            tableData.value = res.data.list
            total.value = res.data.total
        } else {
            ElMessage({
                type: 'error',
                message: `${res.msg}`,
                showClose: true
            })
        }
    } catch (error) {
        ElMessage({
            type: 'error',
            message: `${error}`,
            showClose: true
        })
    }
}

//初始化
getTableData()


</script>

<style lang="scss" scoped>
.edit-info-picture-item-box{
  width: 200px;
  height: 200px;
  margin-right: 10px;
  margin-bottom: 10px;
  cursor: pointer;
}

</style>

<style lang="scss">
</style>